package com.yunchao.library.socket

import com.yunchao.library.socket.logger.SocketLogger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.net.InetSocketAddress
import java.net.Socket


object CommandSender {

    /**
     * 使用协程发送命令
     * @param icCardIp 卡片读写器的IP地址
     * @param icCardPort 卡片读写器的端口号
     * @param deviceNumber 设备编号
     */
    suspend fun sendCommand(icCardIp: String, icCardPort: Int, deviceNumber: String) =
        withContext(Dispatchers.IO) {
            val retryDelayMillis = 1500L
            val maxRetryAttempts = 3
            var attempt = 0

            while (attempt < maxRetryAttempts) {
                attempt++
                runCatching {
                    Socket().use { socket ->
                        // 连接超时设置为5秒
                        socket.connect(InetSocketAddress(icCardIp, icCardPort), 5000)
                        socket.getOutputStream().use { os ->
                            os.write(getCardCommand(deviceNumber).hexStringToByteArray()) // 发送命令
                            os.flush()
                        }
                    }
                }.onSuccess {
                    SocketLogger.logOperation("命令成功发送至 $icCardIp:$icCardPort, 设备: $deviceNumber")
                    return@withContext // 成功发送命令后退出协程
                }.onFailure { e ->
                    SocketLogger.logError("发送命令时出错: ${e.message}")
                    delay(retryDelayMillis) // 重试前延迟一段时间
                }
            }
        }

    /**
     * 扩展函数：将十六进制字符串转换为字节数组
     */
    private fun String.hexStringToByteArray(): ByteArray {
        return chunked(2) { it.toString().toInt(16).toByte() }.toByteArray()
    }

    /**
     * 构造刷卡命令内容
     * @param deviceNumber 设备编号
     * @return 十六进制字符串表示的命令内容
     */
    private fun getCardCommand(deviceNumber: String): String = """
        2020202020313137${Integer.toHexString(deviceNumber.toIntOrNull() ?: 1)}04000161000000000000007B22774465766963654944223A31302C226477436F6D6D616E64223A3230372C22647754696D654F7574223A3132303030302C227754797065223A332C227756657273696F6E223A323536332C226C7044617461223A7B22574F5244223A387D7D
    """.trimIndent()
}